package com.gouqi.tools.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gouqi.gouqitoolscommon.model.entity.User;
import com.gouqi.tools.service.RoleService;
import com.gouqi.tools.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


@Component
public class TraditionRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    //自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取userAccount
        String userAccount = principalCollection.getPrimaryPrincipal().toString();
        // 获取角色列表
        List<String> roles = userService.getUserRolesByUserAccount(userAccount);
        // 获取权限列表
        List<String> permissions = roleService.getRolePermissionsByUserAccount(roles);
        // 封装授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 添加角色
        info.addRoles(roles);
        // 添加权限
        info.addRoles(permissions);
        // 返回
        return info;
    }

    //自定义登录认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1 获取用户身份信息
        String userAccount = token.getPrincipal().toString();
        //2 调用业务层获取用户信息（数据库中）
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = userService.list(queryWrapper).get(0);
        //3 判断并将数据完成封装
        if (user != null) {
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    user.getUserPassword(),
                    token.getPrincipal().toString()
            );
            return authenticationInfo;
        }
        return null;
    }
}